package cc.shacocloud.kotlin.tools.http

import cc.shacocloud.kotlin.tools.Slf4j
import cc.shacocloud.kotlin.tools.Slf4j.Companion.log
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import java.io.IOException

/**
 * 日志拦截器
 *
 * @author 思追(shaco)
 */
@Slf4j
class HttpRequestLoggingInterceptor(private val level: HttpLoggingInterceptor.Level) : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val httpLoggingInterceptor = HttpLoggingInterceptor(matchLogger()).setLevel(level)
        return httpLoggingInterceptor.intercept(chain)
    }

    private fun matchLogger(): HttpLoggingInterceptor.Logger {
        return object : HttpLoggingInterceptor.Logger {
            override fun log(message: String) {
                if (log.isInfoEnabled) {
                    log.info(message)
                }
            }
        }
    }
}
